import config from './config';
import Api from './utils/Api';
App({
  post(apiKey, body = {}, header = {}) {
    return this._request("POST", apiKey, body, header);
  },
  get(apiKey, body = {}, header = {}) {
    return this._request("GET", apiKey, body, header);
  },
  _request(_type, apiKey, body = {}, header = {}) {
    wx.showNavigationBarLoading();
    let that = this;
    let url = (config.isDebug ? config.DEV_URL : config.PRO_URL) + Api[apiKey];
    wx.getStorage({
      key: 'openid',
      success: (res)=>{
        if (!res.data) {
          setTimeout(()=>{
            that.login();
          },500)          
        }
      },
      fail:(res)=>{
        setTimeout(() => {
          that.login();
        }, 500);        
      }
    })
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        data: body,
        method: _type,
        header: {
          'content-type':'application/json'
        },
        success: (d) => {
          wx.hideNavigationBarLoading();
          config.isDebug && console.log(d);
          resolve(d.data);
          // if (d.statusCode === 200) {
          //   resolve(d.data);
          // } else {
          //   reject();
          // }
        },
        fail: (e) => {
          this.toast("网络或服务器错误！");
          reject(e);
        }
      })
    })
  },
  toast(msg) {
    wx.showToast({
      title: msg || "",
      icon: "none"
    })
  },
  login() {
    wx.redirectTo({
      url: '/pages/logs/logs',
    })
  }
})
